using System;

namespace PropertyExpression.CalcExpression
{
    internal class ResultValue<TProperty> : IValue<TProperty>
    {
        public event Action Changed;

        private readonly Func<IValueBase[], TProperty> func;
        private readonly IValueBase[] valueBases;

        private bool isInvalidate;

        public ResultValue(Func<IValueBase[], TProperty> func, params IValueBase[] valueBases)
        {
            this.valueBases = valueBases;
            this.func = func;

            isInvalidate = true;

            foreach (var value in valueBases)
            {
                value.Changed += OnChanged;
            }
        }

        private void OnChanged()
        {
            isInvalidate = true;
            if (Changed != null) Changed();
        }

        private TProperty primVal;

        public TProperty PrimVal
        {
            get
            {
                if (isInvalidate)
                {
                    primVal = func(valueBases);
                    isInvalidate = false;
                }
                return primVal;
            }
        }

        public override string ToString()
        {
            return PrimVal.ToString();
        }
    }
}